package com.dhcc.sds.standard.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.standard.dto.TreeNode;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.service.ISdsStandDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据源定义
 *
 * @ClassName: SdsStandDataSourceController
 * @Description: TODO
 * @author lyh
 */

@Controller
@RequestMapping("${sys.backendPath}/sds/sdsstanddatasource")
public class SdsStandDataSourceController extends BaseController {

    private String PREFIX = "/backend/sds/sdsstanddatasource/";

    @Autowired
    private ISdsStandDataSourceService standDataSourceService;


    /**
     * 跳转到数据源定义列表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "sdsstanddatasource.html";
    }

    /**
     *  获取数据源列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue="0")Map<String,Object>params ) {
        Page<SdsStandSourceEntity> page = new PageFactory<SdsStandSourceEntity>().defaultPage();
        List<SdsStandSourceEntity> result = this.standDataSourceService.page(page,params);
        page.setRecords((List<SdsStandSourceEntity>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }


    /**
     * 获取数据源的tree列表
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> entityTree() {
        return standDataSourceService.getEntityTree();
    }


    /**
     * 跳转新增数据源
     */
    @RequestMapping(value = "/add")
    public String add() {
        return PREFIX + "sdsstanddatasource_add.html";
    }

    /**
     * 新增数据源定义
     */
    @RequestMapping(value = "/to_add")
    @ResponseBody
    public Object add(SdsStandSourceEntity sdsStandSource) {
        if (CommonUtil.isOneEmpty(sdsStandSource)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        sdsStandSource.init();
        standDataSourceService.insert(sdsStandSource);
        return R.ok();
    }

    /**
     * 删除数据源定义
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long sdsStandDataSourceId) {

        this.standDataSourceService.deleteById(sdsStandDataSourceId);

        return R.ok();
    }

    /**
     * 跳转到修改数据源定义
     */
    @RequestMapping(value = "/to_update/{id}")
    public String toUpdate(@PathVariable("id") Long sdsStandDataSourceId, Model model) {
        SdsStandSourceEntity sdsStandDataSource = standDataSourceService.selectById(sdsStandDataSourceId);
        model.addAttribute("parentName",standDataSourceService.getDataNameById(sdsStandDataSource.getParentId()));
        model.addAttribute("sdsStandDataSource",sdsStandDataSource);
        return PREFIX + "sdsstanddatasource_edit.html";
    }

    /**
     * 修改数据源
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(SdsStandSourceEntity sdsStandDataSource) {
        if (CommonUtil.isOneEmpty(sdsStandDataSource)) {
            throw new BizException(BizExceptionEnum.REQUEST_NULL);
        }
        SdsStandSourceEntity old = standDataSourceService.selectById(sdsStandDataSource.getId());

        old.setSourceCode(sdsStandDataSource.getSourceCode());
        old.setSourceDesc(sdsStandDataSource.getSourceDesc());
        old.setIsActive(sdsStandDataSource.getIsActive());
        old.setResume(sdsStandDataSource.getResume());
        old.setWeight(sdsStandDataSource.getWeight());
        old.setParentId(sdsStandDataSource.getParentId());
        old.init();
        standDataSourceService.updateAllColumnById(old);
        return R.ok();
    }

    /**
     * 跳转导入数据源页面
     * @param parentId
     * @param model
     * @return
     */
    @RequestMapping("/to_import/{parentId}")
    public String toImport(@PathVariable Long parentId, Model model) {
        model.addAttribute("parentId", parentId);
        return PREFIX + "sdsstanddatasource_import.html";
    }

    @RequestMapping(method = RequestMethod.POST, path = "/import")
    @ResponseBody
    public R importData(@RequestPart("file") MultipartFile file, @RequestParam("parentId") Long parentId) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> all = reader.read();
            this.standDataSourceService.importData(all, parentId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return R.ok();
    }


    /**
     *  导出数据源
     */
    @RequestMapping("/export")
    public void exportData(HttpServletRequest request, HttpServletResponse response) {
        List<SdsStandSourceEntity> result = this.standDataSourceService.exportData();
        // 通过工具类创建writer，默认创建xls格式
        BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
        // 一次性写出内容，使用默认样式
        if (CommonUtil.isNotEmpty(result)) {
            ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
            for (SdsStandSourceEntity obj : result) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("数据源编码",obj.getSourceCode());
                row.put("数据源名称",obj.getSourceDesc());
                row.put("备注",obj.getResume());
                rows.add(row);
            }
            writer.write(rows);
            writer.setColumnWidth(0, 20);
            writer.setColumnWidth(1, 30);
            writer.setColumnWidth(2, 40);
        } else {
            List<String> row = CollUtil.newArrayList("无数据");
            List<List<String>> rows = new ArrayList<List<String>>();
            rows.add(row);
            writer.write(rows);
        }

        ServletOutputStream out = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "数据源_" + sdf.format(new Date()) + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
            out = response.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            writer.flush(out);
            // 关闭writer，释放内存
            writer.close();
        }
    }


    /**
     *  下拉树
     */
    @RequestMapping("/getDataSourceTree")
    @ResponseBody
    public Object getDataSourceTree(){
        /*Long parentId = 0l;
        List<TreeNode> dataSourceTree = standDataSourceService.getDataSourceTree(parentId);*/
        List<Tree<Long>> trees = standDataSourceService.getDataSourceTree2();
        return trees;
    }
}
